//
//  ZXDiscoverSearchBar.m
//  ZXOCWeiBo
//
//  Created by mac on 15/11/29.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZXDiscoverSearchBar.h"

@interface ZXDiscoverSearchBar()<UITextFieldDelegate>

/**
 *  文本框
 */
@property (weak, nonatomic) IBOutlet UITextField *texxtField;
/**
 *  取消按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
/**
 *  文本框右边的约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textFieldRightConstraint;

/**
 *  查找图标的image
 */
@property(nonatomic,strong)UIImageView* searchImagView;

/**
 *  箭头按钮
 */
@property(nonatomic,strong)UIButton* arrowBtn;
@end

@implementation ZXDiscoverSearchBar

+(instancetype)searchBar
{
    return [NSBundle loadViewFromNibName:@"ZXDiscoverSearchBar"];
}

-(void)awakeFromNib
{
    
    self.texxtField.leftView = self.searchImagView;
    
    //设置左边View显示模式 一定要设置，否则不显示
    self.texxtField.leftViewMode = UITextFieldViewModeAlways;
    
    //设置代理
    self.texxtField.delegate = self;
}

#pragma mark 文本输入框代理
/**
 *  当要输入文字的时候调用这个方法
 */
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    //设置按钮为可选状态
    self.cancelBtn.hidden = NO;
    
    //设置文本框右边的约束的距离
    self.textFieldRightConstraint.constant = self.cancelBtn.w;
    
    //更改左边按钮的样式
    self.texxtField.leftView = self.arrowBtn;
    
    self.texxtField.leftViewMode = UITextFieldViewModeAlways;
    
    return YES;
}
/**
 * 监听取消按钮的点击
 */
- (IBAction)cancelBtnClick
{
    //恢复约束
    self.textFieldRightConstraint.constant = 0;
    
    //添加动画效果
    //约束动画不能吧约束改变直接放在block中
    [UIView animateWithDuration:0.25 animations:^{
        //要添加使用，调用父控件的layoutIfNeeded方法
        [self layoutIfNeeded];
    }];
    
    //隐藏按钮
    self.cancelBtn.hidden = YES;
    
    //再次更改左边显示的图片
    self.texxtField.leftView = self.searchImagView;
    
    [self endEditing:YES];
}

#pragma mark 懒加载

-(UIImageView *)searchImagView
{
    if (!_searchImagView)
    {
        //添加texxtField
        UIImageView * searchImagView = [[UIImageView alloc]init];
        
        UIImage * searchImg = [UIImage imageNamed:@"searchbar_textfield_search_icon"];
        searchImagView.image = searchImg;
        
        //设置图片不拉伸
        searchImagView.contentMode = UIViewContentModeCenter;
        
        searchImagView.bounds = CGRectMake(0, 0, searchImg.size.width+15, searchImg.size.height);
        _searchImagView = searchImagView;
    }
    return _searchImagView;
}

-(UIButton *)arrowBtn
{
    if (!_arrowBtn)
    {
        //设置自定义按钮样式
        _arrowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_arrowBtn setImage:[UIImage imageNamed:@"popover_arrow"] forState:UIControlStateNormal];
        
        _arrowBtn.bounds = self.searchImagView.bounds;
        
        //让图片空间旋转180度
        _arrowBtn.imageView.transform = CGAffineTransformMakeRotation(M_PI);
    }
    return _arrowBtn;
}

@end
